<template>
  <div class="all">
    <el-drawer
      v-model="tableStatus"
      :title="t('dataDictionary.dictionaryList')"
      direction="rtl"
      @close="handleClose()"
      size="50%"
    >
      <el-main class="main-box">
        <div class="mb-content">
          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            status-icon
            :inline="true"
            label-width="60px"
            class="demo-ruleForm"
          >
            <el-form-item :label="t('dataDictionary.name')" prop="name">
              <el-input v-model="ruleForm.name" autocomplete="off"  />
            </el-form-item>
            <el-form-item :label="t('dataDictionary.status')" prop="status">
              <el-select v-model="ruleForm.status">
                <!-- <el-option :label="t('dataDictionary.normal')" value="1" />
                <el-option :label="t('formDemo.disabled')" value="2" /> -->
                <el-option
                  v-for="(item, index) in statusOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm(ruleFormRef)">{{
                t('dataDictionary.search')
              }}</el-button>
              <el-button @click="resetForm(ruleFormRef)">{{ t('common.reset') }}</el-button>
            </el-form-item>
          </el-form>
          <el-button type="primary" @click="onOpenDia">{{ t('exampleDemo.add') }}</el-button>

          <el-table :data="tableData" style="width: 100%" :row-class-name="tableRowClassName">
            <el-table-column label="名称" prop="itemText" />
            <el-table-column label="key" prop="itemValue" />
            <el-table-column :label="t('formDemo.operate')" align="center">
              <template #default="scope">
                <span class="o-btn" @click="handleEdit(scope.$index, scope.row)">{{
                  t('exampleDemo.edit')
                }}</span>
                |
                <el-popover :visible="scope.row.visibleStatus" placement="top" :width="160">
                  <p>确定删除吗?</p>
                  <div style="text-align: right; margin: 0">
                    <el-button size="small" text @click="scope.row.visibleStatus = false">{{
                      t('common.cancel')
                    }}</el-button>
                    <el-button
                      size="small"
                      type="primary"
                      @click="confirmDelete(scope.$index, scope.row)"
                    >
                      {{ t('common.ok') }}</el-button
                    >
                  </div>
                  <template #reference>
                    <span class="o-btn" @click="handleDelete(scope.$index, scope.row)">{{
                      t('formDemo.delete')
                    }}</span>
                  </template>
                </el-popover>
              </template>
            </el-table-column>
          </el-table>
          <div class="page-box">
            <el-pagination
              v-show="tableData.length > 0"
              v-model:current-page="sidebarCurrentPage4"
              v-model:page-size="sidebarPageSize4"
              :page-sizes="[10, 20, 30, 40]"
              :small="sidebarSmall"
              :disabled="sidebarDisabled"
              :background="sidebarBackground"
              layout="total, sizes, prev, pager, next"
              :total="sidebarTotal"
              @size-change="sidebarHandleSizeChange"
              @current-change="sidebarHandleCurrentChange"
            />
          </div>
        </div>
      </el-main>
      <!-- 添加弹框 -->
      <el-dialog v-model="dialogFormVisible" :title="drawerTitle" @close="refreshData" width="40%">
        <el-form :model="form" ref="ruleFormRef2" :rules="rules">
          <el-form-item label="名称" :label-width="formLabelWidth" prop="itemText">
            <el-input v-model="form.itemText" placeholder="请输入"  maxlength="30" />
          </el-form-item>
          <el-form-item label="key" :label-width="formLabelWidth" prop="itemValue">
            <el-input
              v-model="form.itemValue"
              placeholder="请输入"
              maxlength="30"
            />
          </el-form-item>
          <el-form-item label="slot名称" :label-width="formLabelWidth" prop="slotText" >
              <el-input v-model="form.slotText" placeholder="请输入"  maxlength="30" />
          </el-form-item>
          <el-form-item label="宽度" :label-width="formLabelWidth" prop="width" >
              <el-input v-model="form.width" placeholder="请输入"  maxlength="30" />
          </el-form-item>
          <el-form-item label="是否排序" :label-width="formLabelWidth" prop="sortOderFlag">
              <el-switch
                      v-model="form.sortOderFlag"
                      inline-prompt
                      :active-value="1"
                      :inactive-value="0"
                      active-text="启用"
                      inactive-text="禁用"
              />
          </el-form-item>
          <el-form-item label="排序值" :label-width="formLabelWidth" prop="sortOrder">
            <el-input-number
              v-model="form.sortOrder"
              controls-position="right"
              @change="handleChangeInput"
            />
          </el-form-item>
          <el-form-item label="是否启用" :label-width="formLabelWidth" prop="status">
            <el-switch
              v-model="form.status"
              inline-prompt
              :active-value="1"
              :inactive-value="0"
              active-text="启用"
              inactive-text="禁用"
            />
          </el-form-item>
          <el-form-item label="备注" :label-width="formLabelWidth" prop="remark">
              <el-input v-model="form.remark" maxlength="300" show-word-limit type="textarea" />
          </el-form-item>
        </el-form>
        <template #footer>
          <hr />
          <span class="dialog-footer">
            <el-button @click="resetForm2(ruleFormRef2)">关闭</el-button>
            <el-button type="primary" @click="submitForm2(ruleFormRef2)"> 确定 </el-button>
          </span>
        </template>
      </el-dialog>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import { ElDrawer, ElMessage } from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import type { FormInstance, FormRules } from 'element-plus'
import { sendDataDictList } from '../index'
import { vCheckVal } from '@/directives/checkVal'
import {
  getDataDictList,
  dictItemAdd,
  dictItemEdit,
  dictItemDelete
} from '@/api/tableManagement/index'
import { timestamp } from '@/views/SysMonitor/monitor/common'
const tableStatus = ref(false)
const { t } = useI18n()
const drawerTitle = ref('')
const addDataDialog = () => {
  drawerTitle.value = '新增'
  dialogFormVisible.value = true
}
const editDataDialog = () => {
  drawerTitle.value = '编辑'
  dialogFormVisible.value = true
}
// 状态下拉
const statusOptions = [
  { label: '正常', value: 1 },
  { label: '禁用', value: 0 }
]
// 接收传值
const props = defineProps<{
  dicSet: boolean
}>()
watch(
  () => props.dicSet,
  (newval: boolean, oldval: boolean) => {
    // console.log(newval, oldval)
    tableStatus.value = newval
  }
)
// 关闭的时候传给父组件
// 2、定义发射给父组件的方法
const emit = defineEmits(['sidebarClose'])
const handleClose = () => {
  // console.log(props.dicSet, 'props.dicSet')
  tableStatus.value = false
  emit('sidebarClose', tableStatus.value)
}
const ruleFormRef = ref<FormInstance>()
const ruleFormRef2 = ref<FormInstance>()

const ruleForm = reactive({
  name: '',
  status: ''
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      // if (ruleForm.name || ruleForm.status) {
      sendDataDictList.itemText = ruleForm.name
      sendDataDictList.status = ruleForm.status
      // }
      getChildrenList()
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  sendDataDictList.itemText = ''
  sendDataDictList.status = ''
  getChildrenList()
}

// table
interface User {
  itemText: string
  itemValue: string
  dictId: string
  id: string
}
let tableData = ref<User[]>([])

//打开删除弹窗
const handleDelete = (index: number, row: any) => {
  // console.log(index, row)
  delePop()
  row.visibleStatus = true
}
// 确定删除
const confirmDelete = async (index: number, row: any) => {
  let { result, code } = await dictItemDelete(row.id )
  if (Number(code) == 200) {
    getChildrenList()
    ElMessage({
      message: result.message,
      type: 'success'
    })
  } else {
    ElMessage.error(result.message)
  }
}
// 全部关闭
const delePop = () => {
  tableData.value.map((item: any) => {
    item.visibleStatus = false
  })
}

// 分页
const sidebarCurrentPage4 = ref(1)
const sidebarPageSize4 = ref(1)
const sidebarSmall = ref(false)
const sidebarBackground = ref(false)
const sidebarDisabled = ref(false)
const sidebarTotal = ref(1)
const sidebarHandleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  sendDataDictList.itemText = ruleForm.name
  sendDataDictList.status = ruleForm.status
  sendDataDictList.pageNo = 1
  sidebarCurrentPage4.value = 1
  sendDataDictList.pageSize = val
  getChildrenList()
}
const sidebarHandleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  sendDataDictList.itemText = ruleForm.name
  sendDataDictList.status = ruleForm.status
  sendDataDictList.pageNo = val
  getChildrenList()
}
// 添加弹框
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'
//获取列表
const getChildrenList = async () => {
  let {
    result: { total, size, records }
  } = await getDataDictList(sendDataDictList)
  //records
  tableData.value = JSON.parse(JSON.stringify(records))
  delePop()
  sidebarTotal.value = total
  sidebarPageSize4.value = size
}
// 接受字典配置参数
const dictConfig: any = async (params) => {
  // console.log(params, 'params')
  sendDataDictList.dictId = params.id
  form.value.dictId = params.id
  getChildrenList()
  // console.log(tableData.value, 'tableData')
}
interface formType {
    itemText: string
    itemValue: string
    slotText?: string | number
    width: string | number
    sortOderFlag: string | number
    sortOrder: string | number
    status?: string | number
    remark: string
  id?: string | number
}
let form = ref<formType>({
    itemText: '', // 名称
    itemValue: '', // key值
    slotText: '', // slot名称
    width: '', // 宽度
    sortOderFlag: '', // 是否排序
    sortOrder: 0, // 排序
    status: 1, // 启用状态
    remark: '1', // 备注
    id: '' // 名称
})
const onOpenDia = () => {
  addDataDialog()
  // form.value.dictId = ''
  form.value.itemText = ''
  form.value.itemValue = ''
  form.value.slotText = ''
  form.value.width = ''
  form.value.sortOderFlag = ''
  form.value.sortOrder = 0
  form.value.status = 1
  form.value.remark = ''
  form.value.id = ''
}
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入名称'))
  } else {
    callback()
  }
}
const validatePass2 = async (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入数据值'))
  } else {
    let result = await checkValue()
    //console.log(result, 'result')
    if (result.code == '200') {
      callback()
    } else {
      callback(new Error(result.message))
    }
  }
}
const rules = reactive<FormRules>({
    itemText: [{ required: true, message: '请输入名称', trigger: 'blur' }],
    itemValue: [{ required: true, message: '请输入key', trigger: 'blur' }],
})

// 添加提交
const submitForm2 = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      //console.log(form.value, 'form', form.value.dictId)
      if (drawerTitle.value == '编辑') {
        let result = await dictItemEdit(form.value)
        if (result.code == '200') {
          dialogFormVisible.value = false
          getChildrenList()
          ElMessage({
            message: result.message,
            type: 'success'
          })
        } else {
          ElMessage.error(result.message)
        }
      } else {
        // //console.log(form.value, 'form')
        let result = await dictItemAdd(form.value)
        if (result.code == '200') {
          dialogFormVisible.value = false
          getChildrenList()
          ElMessage({
            message: result.message,
            type: 'success'
          })
        } else {
          ElMessage.error(result.message)
        }
      }
      // dialogFormVisible.value = false
    } else {
      //console.log('error submit!')
      return false
    }
  })
}

const resetForm2 = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  if (drawerTitle.value == '新增') {
    formEl.resetFields()
  }
  dialogFormVisible.value = false
}
const refreshData = () => {
  dialogFormVisible.value = false
  if (drawerTitle.value == '新增') {
    ruleFormRef2.value?.resetFields()
  }
}
const handleChangeInput = (value: number) => {
  //console.log(value, form.value.sortOrder)
}
const handleEdit = async (index: number, row: any) => {
  editDataDialog()
  form.value = JSON.parse(JSON.stringify(row))
  // form.value = row
  form.value.status = Number(form.value.status)
  // console.log(form, 'row')
}
// 校验重复字典

const checkValue = async () => {
  // console.log(form.value.itemValue)
  let params = {
    _t: timestamp(),
    dictId: form.value.dictId,
    itemValue: form.value.itemValue
  }
  if (form.value.id) {
    params.id = form.value.id
  }
  let result = await getDictItemCheck(params)
  return result
}
//区分正常禁用状态
const tableRowClassName = ({ row, rowIndex }: { row: any; rowIndex: number }) => {
  if (row.status === 1) {
    return 'success-row'
  } else {
    return 'warning-row'
  }
  return ''
}
defineExpose({
  dictConfig
})
</script>

<style scoped>
:deep(.el-drawer__header) {
  margin-bottom: 0;
}

.main-box {
  border-top: 1px solid #ccc;
}

.mb-content {
  border: 1px solid #ccc;
  padding: 15px 5px;
}

.page-box {
  overflow: hidden;

  .el-pagination {
    float: right;
    margin-top: 20px;
  }
}

.o-btn {
  color: #409eff;
  padding: 0 5px;
  cursor: pointer;
}

.dialog-footer {
  display: block;
  padding-top: 10px;
}

:deep(.el-table .warning-row) {
  background: #f4f4f4;
  color: #bababa;
}
</style>
